#!/bin/bash
# $Id: echo_common,v 1.4 2004/11/16 06:17:33 repeater Exp $
# $Log: echo_common,v $
# Revision 1.4  2004/11/16 06:17:33  repeater
# Added TBD_COMMAND.
# Enhanced PARSEHOSTS for RH 6.x users.
#
# Revision 1.3  2004/09/12 20:36:06  repeater
# Escape search string in parsehosts.
#
# Revision 1.2  2004/09/12 19:00:29  repeater
# Add parsehosts function.
#
# Revision 1.1  2004/08/03 19:38:08  repeater
# Initial revision
#
########################################################################
# Convenience Functions
########################################################################
# Logging
function log {
   MESSAGE="EchoIRLP: $@"
   echo "$MESSAGE"
   if [ -n "$LOGFILE" ]; then
      echo "`date '+%b %d %Y %T %z'` $MESSAGE" >> $LOGFILE
   fi
}

# Only execute a tbdcmd if tbd is running.
TBD_COMMAND() {
	local pid
	pid=`/sbin/pidof -o $$ -o $PPID -o %PPID -x tbd`
	if [ "$pid" = "" ] ; then
		log "tbd is not running..."
		return 1
	fi
	$ECHO_TBD_COMMAND "$@"
	return
}
# Search and parse a record from the tbd hosts file.
function parsehosts {
	HOSTSIP=""
	HOSTSCALL=""
	HOSTSNUM=""
	# Check to see if an argument exists
	if [ "$#" -ne "1" ]; then 
		echo "usage: parsehosts [number][call-sign]"
		echo "Sets vars \$HOSTSIP, \$HOSTSCALL and \$HOSTSNUM from"
		echo "tbd hosts file."
		return
	fi
	#local ESCSTR=`echo "$1" | sed 's/\*/\\\*/g'`
	#echo "$ESCSTR"
	if [ -f "$ECHO_TBD_DATA/hosts-all" ] ; then
		local ECHOHOSTS="$ECHO_TBD_DATA/hosts-all"
	else
		local ECHOHOSTS="$ECHO_TBD_DATA/hosts"
	fi
	set `echo "$1" | sed 's/\*/\\\*/g'`
	# If argument is numeric set search match for end of line node number.
	# otherwise search match for with leading & trailing white space.
	if [ `echo "$1" | egrep '^[0-9]+$'` &> /dev/null ]; then
		# argument must be an unsigned integer!
		local SRCH="[[:space:]]$1$"
	else
		local SRCH="[[:space:]]$1[[:space:]]"
	fi
	# First determine which vendor we have: RedHat or Fedora
	RH_REL=/etc/redhat-release
	if [ -f $RH_REL ]; then
		REL=`cat $RH_REL`
	fi
	case $REL in
		"Red Hat Linux release 6"*)
			local MAXCNT=" "
			;;
		*)
		local MAXCNT="--max-count=1"
		;;
	esac
	eval `grep -i $MAXCNT "$SRCH" "$ECHOHOSTS" | \
		sed s/\ // | sed s/\#// | \
		awk -F'\t' '{ \
		print "HOSTSIP="$1;print "HOSTSCALL="$2;print "HOSTSNUM="$3 \
		}'`
}

########################################################################
# Standard Opening Tests
########################################################################
# Make sure we are user repeater!!!
if [ "`/usr/bin/whoami`" != "repeater" ] ; then
  echo "${0##*/}:  must be run as user REPEATER!"
  exit 1
fi

# Make sure we have sourced the IRLP environment file
if [ "$RUN_ENV" != "TRUE" ] ; then
  echo -n "Loading IRLP environment ... "
  . /home/irlp/custom/environment
  echo "DONE"
fi

# Make sure we have sourced the EchoIRLP environment file
if [ "$ECHO_ENV" != "TRUE" ] ; then
  echo -n "Loading EchoIRLP environment ... "
  . /home/irlp/custom/environment
  echo "DONE"
fi

